/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package beans;

import java.lang.annotation.Annotation;
import java.util.List;
import javax.ejb.Singleton;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import persistance.model.AllowedRole;
import persistance.model.User;
import persistance.model.UserRole;

/**
 *
 * @author Bobok
 */
@Singleton
public class JPAUserDAO implements UserDAOLocal {

    @PersistenceContext(unitName = "Rescriptus-ejbPU")
    private EntityManager em;

    public User getUser(String username) {
        User user = em.find(User.class, username);
        return user;
    }

    public User verify(String username, String password) {
        User user = getUser(username);
        if (user != null && user.getPassword().equals(password)) {
            return user;
        }
        return null;
    }

    public List<User> getUsersByRole(UserRole role) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public void deleteUser(User user) {
        em.remove(user);
    }

    public void persist(Object object) throws Exception {
        em.persist(object);
    }

    public void remove(Object object) throws Exception {;
        Object merged = em.merge(object);
        em.remove(merged);
    }

    public Object getUserByEmail(String email) {
        Query db = em.createQuery("select u from User u where u.email = :email");
        db.setParameter("email", email);
        if (!db.getResultList().isEmpty()){
            return db.getResultList().get(0);
        }
        return null;
    }

    public List<AllowedRole> getAllowedRoles() {
        TypedQuery<AllowedRole> db = em.createQuery("select r from AllowedRole r", AllowedRole.class);
        return db.getResultList();
    }

    public void deleteAllowedRole(AllowedRole role) {
        em.remove(role);
    }
}
